import Vue from "vue";
import Vuex from "vuex";
import request from "../utils/request";

Vue.use(Vuex);

const store = new Vuex.Store({
  actions: {
   async getCartList(context){
     let list =  await request({
        url: "/ShopCountInfo",
        // method: "get"
      })
      console.log("cartList:", list);
      context.commit('UPDATE_CART_LIST',list)
    },
    async updateCount(context,params){
    let flag  = await request({
        url:"/updateItemCount",
        params  
      })
      if(flag === "success"){
        context.commit('UPDATE_COUNT',params) 
    }
  },
  },
  mutations: {
      UPDATE_CART_LIST(state,list){
          state.cartList = list
      },
      UPDATE_COUNT(state,params){
        let item = state.cartList.find(item => item.id === params.id);
        item.count = params.count
      },
  },
  state: {
    cartList: [],
  },
  getters: {
    totalCount(state){
    return  state.cartList.reduce((totalCount,item) => totalCount + item .count,0)
    },
    totalAmount(state){
        return state.cartList.reduce((totalAmount,item)=>totalAmount+item.price*item.count,0)
    }
  
  }
});

export default store;












/* 
export default new Vuex.Store({
  state: {
    cartItems: []
  },
  
  getters: {
    totalItems: state => {
      return state.cartItems.reduce((sum, item) => sum + item.count, 0)
    },
    totalPrice: state => {
      return state.cartItems.reduce((sum, item) => sum + item.price * item.count, 0)
    }
  },
  
  mutations: {
    SET_CART_ITEMS(state, items) {
      state.cartItems = items
    },
    UPDATE_ITEM_COUNT(state, { id, count }) {
      const item = state.cartItems.find(item => item.id === id)
      if (item) {
        item.count = count
      }
    },
    setCartItems(state, items) {
      state.cartItems = items.map(item => ({
        ...item,
        image: item.image || '',
      }))
    }
  },
  
  actions: {
    async fetchCartItems({ commit }) {
      try {
        console.log('开始请求购物车数据...')
        const { data } = await axiosInstance.get('/ShopCountInfo')
        console.log('购物车数据响应:', data)
        if (Array.isArray(data)) {
          commit('setCartItems', data)
        } else {
          console.error('返回的数据格式不正确:', data)
          commit('setCartItems', [])
        }
      } catch (error) {
        console.error('获取购物车数据失败:', error.response || error)
        commit('setCartItems', [])
      }
    },
    
    async updateItemCount({ commit }, { id, count }) {
      try {
        const response = await axiosInstance.get(`/updataItemCount`, {
          params: {
            id: id,
            count: count
          }
        });
        
        if (response.data === 'success') {
          commit('UPDATE_ITEM_COUNT', { id, count });
        } else {
          console.error('更新失败:', response.data);
        }
      } catch (error) {
        console.error('更新商品数量失败:', error);
      }
    }
  }
})  */
